from flask import Flask, request, jsonify
import json
from datetime import datetime
from pathlib import Path
import schedule
import time
import threading
import logging
from tools.checkhfileinit import RepoUtils, CommonUtils
from tools.diffanalyzerlimit import DiffAnalyzer

# 创建日志目录
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_dir / 'webhook_receiver.log', encoding='utf-8'),
        logging.FileHandler(log_dir / f'webhook_receiver_{datetime.now().strftime("%Y%m%d")}.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

current_dir = Path.cwd()
check_work_dir = current_dir / "check_work"
base_dir = current_dir / "base"
diff_dir = current_dir / "diff"
master_dir = current_dir / "master"
script_path = current_dir / "tools/get_hifle_counts.py"

logger = logging.getLogger('WSL_Webhook_Receiver')

app = Flask(__name__)

@app.route('/webhook', methods=['POST', 'GET'])
def webhook_receiver():
    try:
        # 处理POST请求（webhook数据）
        logger.info("=" * 80)
        logger.info("收到新的Webhook请求")
        
        # 获取头信息
        headers = dict(request.headers)
        event_type = headers.get('X-Gitee-Event', 'unknown')
        logger.info(f"事件类型: {event_type}")
        
        # 获取JSON数据
        data = request.get_json()
        
        if not data:
            logger.warning("未收到JSON数据")
            return jsonify({'error': 'No JSON data received'}), 400
        
        # 记录基本信息
        repo_name = data.get('repository', {}).get('full_name', 'unknown')
        sender = data.get('sender', {}).get('login', 'unknown')
        action = data.get('action', '')
        logger.info(f"仓库: {repo_name}")
        logger.info(f"发送者: {sender}")
        logger.info(f"动作: {action}")

        pr_number = data.get('pull_request', {}).get('number')
        pr_url = f"https://gitee.com/{repo_name}/pulls/{pr_number}"
        logger.info(f"PR链接: {pr_url}")
        
        diffCheck = DiffAnalyzer()
        logger.info("开始下载PR diff")
        diffText = diffCheck.download_pr_diff(repo_name, pr_number, "4e733f805654043c881e5b43df5e2129")
        logger.info("下载 diff 成功")
        
        if diffCheck.analyze_diff(diffText):
            logger.info("PR 需要检查头文件")
            diffPath = diffCheck.save_diff(diffText, pr_number, diff_dir)
            logger.info(f"Diff文件保存路径: {diffPath}")
            
            logger.info("创建虚拟工作空间")
            diffCheck.create_virtual_workspace(Path(diffPath), check_work_dir, base_dir)

            diff_hfile_counts = Path(diffPath).parent / "diff_hfile_counts.txt"
            base_hfile_counts = Path(diffPath).parent.parent / "hfile_counts.txt"
            
            logger.info("开始对比文件")
            diffCheck.compare_files(base_hfile_counts, diff_hfile_counts, pr_number)
            logger.info("对比结果已保存")
        else:
            logger.info("PR 不需要检查, 门禁通过")

        logger.info(f"PR处理完成: {pr_url}")
        logger.info("Webhook处理完成")
        logger.info("=" * 80)
        
        return jsonify({
            'status': 'success',
            'message': 'Webhook received in WSL',
            'event': event_type,
            'repository': repo_name,
            'pr_number': pr_number,
            'timestamp': datetime.now().isoformat()
        })
    
    except Exception as e:
        logger.error(f"处理Webhook时出错: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500

def Init():
    """初始化函数"""
    try:
        logger.info("开始执行初始化任务")
        logger.info(f"同步仓库到: {master_dir}")
        
        # 同步仓库
        sync_success = RepoUtils.check_and_sync_repo(
            "https://gitee.com/openharmony/manifest.git", 
            "master", 
            master_dir
        )
        
        if not sync_success:
            logger.error("仓库同步失败")
            return False
        
        # 运行分析
        logger.info("运行Python分析脚本")
        analysis_success = CommonUtils.run_python_analysis(master_dir, str(script_path))
        
        if not analysis_success:
            logger.error("代码分析失败")
            return False
        
        # 备份结果
        logger.info("备份分析结果")
        backup_success = CommonUtils.backup_analysis_results(master_dir, base_dir, diff_dir)
        
        if not backup_success:
            logger.warning("分析结果备份部分失败")
        
        logger.info("初始化任务完成")
        return True
        
    except Exception as e:
        logger.error(f"初始化任务执行失败: {e}", exc_info=True)
        return False

def run_scheduler():
    """运行定时任务的线程函数"""
    logger.info("定时任务调度器启动")
    while True:
        try:
            schedule.run_pending()
            time.sleep(60)  # 每分钟检查一次是否有任务需要执行
        except Exception as e:
            logger.error(f"定时任务调度器出错: {e}")
            time.sleep(300)  # 出错后等待5分钟再继续

if __name__ == '__main__':
    logger.info("=" * 80)
    logger.info("初始化 check header 环境")
    logger.info(f"工作目录: {current_dir}")
    logger.info(f"Master目录: {master_dir}")
    logger.info(f"Base目录: {base_dir}")
    logger.info(f"Diff目录: {diff_dir}")
    
    # 首次执行初始化
    Init()
    
    # 设置定时任务（每5分钟执行一次）
    schedule.every(5).hours.do(Init)
    logger.info("定时任务设置：每5分钟执行一次初始化")
    
    # 启动定时任务线程
    scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
    scheduler_thread.start()
    logger.info("定时任务线程已启动")
    
    # 启动Flask应用
    logger.info("启动Flask Web服务器...")
    logger.info(f"服务地址: http://0.0.0.0:3000")
    logger.info(f"健康检查: http://0.0.0.0:3000/health")
    logger.info(f"状态检查: http://0.0.0.0:3000/status")
    logger.info("=" * 80)
    
    try:
        app.run(host='0.0.0.0', port=3000, debug=False)
    except Exception as e:
        logger.error(f"Flask服务器启动失败: {e}")
        logger.info("尝试使用端口3001...")
        app.run(host='0.0.0.0', port=3001, debug=False)